<template>
  <div class="product-detail-container">
    <div class="product-content" v-loading="loading">
      <!-- 商品基本信息 -->
      <div class="product-basic">
        <div class="product-gallery">
          <el-carousel
            :interval="4000"
            type="card"
            height="400px"
            indicator-position="outside"
          >
            <el-carousel-item v-for="image in product.images" :key="image">
              <el-image
                :src="image"
                :preview-src-list="product.images"
                fit="cover"
                class="product-image"
              />
            </el-carousel-item>
          </el-carousel>
        </div>

        <div class="product-info">
          <h1 class="product-name">{{ product.name }}</h1>
          
          <div class="product-price">
            <span class="current-price">¥{{ product.price.toFixed(2) }}</span>
            <span class="original-price" v-if="product.originalPrice">
              ¥{{ product.originalPrice.toFixed(2) }}
            </span>
          </div>

          <div class="product-tags" v-if="product.tags?.length">
            <el-tag
              v-for="tag in product.tags"
              :key="tag"
              :type="tag.type"
              size="small"
            >
              {{ tag.label }}
            </el-tag>
          </div>

          <div class="product-stock">
            库存：<span :class="{ 'stock-warning': product.stock <= 5 }">
              {{ product.stock }} 件
            </span>
          </div>

          <!-- 规格选择 -->
          <div class="product-specs">
            <div
              v-for="spec in product.specifications"
              :key="spec.name"
              class="spec-item"
            >
              <div class="spec-name">{{ spec.name }}：</div>
              <div class="spec-values">
                <el-radio-group
                  v-if="spec.type === 'radio'"
                  v-model="selectedSpecs[spec.name]"
                  @change="handleSpecChange"
                >
                  <el-radio
                    v-for="value in spec.values"
                    :key="value"
                    :label="value"
                    :disabled="!isSpecAvailable(spec.name, value)"
                  >
                    {{ value }}
                  </el-radio>
                </el-radio-group>

                <el-checkbox-group
                  v-else-if="spec.type === 'checkbox'"
                  v-model="selectedSpecs[spec.name]"
                  @change="handleSpecChange"
                >
                  <el-checkbox
                    v-for="value in spec.values"
                    :key="value"
                    :label="value"
                    :disabled="!isSpecAvailable(spec.name, value)"
                  >
                    {{ value }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>

          <!-- 数量选择 -->
          <div class="product-quantity">
            <span class="quantity-label">数量：</span>
            <el-input-number
              v-model="quantity"
              :min="1"
              :max="product.stock"
              :disabled="product.stock <= 0"
              @change="handleQuantityChange"
            />
          </div>

          <!-- 操作按钮 -->
          <div class="product-actions">
            <el-button
              type="primary"
              size="large"
              :disabled="!isAddToCartEnabled"
              @click="handleAddToCart"
            >
              加入购物车
            </el-button>
            <el-button
              type="danger"
              size="large"
              :disabled="!isAddToCartEnabled"
              @click="handleBuyNow"
            >
              立即购买
            </el-button>
            <el-button
              :type="isFavorite ? 'danger' : 'default'"
              size="large"
              @click="handleToggleFavorite"
            >
              <el-icon><Star /></el-icon>
              {{ isFavorite ? '已收藏' : '收藏' }}
            </el-button>
            <el-button
              type="default"
              size="large"
              @click="handleShare"
            >
              <el-icon><Share /></el-icon>
              分享
            </el-button>
          </div>
        </div>
      </div>

      <!-- 商品详细信息 -->
      <div class="product-detail">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="商品详情" name="detail">
            <div class="detail-content" v-html="product.detail"></div>
          </el-tab-pane>
          <el-tab-pane label="规格参数" name="params">
            <el-descriptions :column="2" border>
              <el-descriptions-item
                v-for="param in product.parameters"
                :key="param.name"
                :label="param.name"
              >
                {{ param.value }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="售后服务" name="service">
            <div class="service-content">
              <h3>退换货政策</h3>
              <p>{{ product.returnPolicy }}</p>
              <h3>配送说明</h3>
              <p>{{ product.shippingInfo }}</p>
              <h3>售后保障</h3>
              <p>{{ product.afterSalesService }}</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 推荐商品 -->
      <div class="recommend-products" v-if="recommendList.length">
        <h3>猜你喜欢</h3>
        <el-row :gutter="20">
          <el-col
            v-for="item in recommendList"
            :key="item.id"
            :xs="12"
            :sm="8"
            :md="6"
            :lg="4"
          >
            <el-card
              class="product-card"
              :body-style="{ padding: '0px' }"
              @click="handleProductClick(item)"
            >
              <el-image
                :src="item.image"
                fit="cover"
                class="product-image"
              />
              <div class="product-info">
                <h4 class="product-name">{{ item.name }}</h4>
                <p class="product-price">¥{{ item.price.toFixed(2) }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, Share } from '@element-plus/icons-vue'
import { useCartStore } from '@/stores/cart'
import {
  getProductDetail,
  getRecommendProducts,
  addToCart,
  toggleFavorite,
  shareProduct
} from '@/api/product'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()

// 状态
const loading = ref(false)
const product = ref({})
const recommendList = ref([])
const quantity = ref(1)
const activeTab = ref('detail')
const isFavorite = ref(false)
const selectedSpecs = ref({})

// 计算属性
const isAddToCartEnabled = computed(() => {
  // 检查是否选择了所有必选规格
  const requiredSpecs = product.value.specifications?.filter(
    spec => spec.required
  ) || []
  
  return requiredSpecs.every(spec => {
    const value = selectedSpecs.value[spec.name]
    return value && (Array.isArray(value) ? value.length > 0 : true)
  })
})

// 获取商品详情
const loadProductDetail = async () => {
  try {
    loading.value = true
    const res = await getProductDetail(route.params.id)
    product.value = res.data
    
    // 初始化规格选择
    product.value.specifications?.forEach(spec => {
      if (spec.type === 'radio') {
        selectedSpecs.value[spec.name] = ''
      } else if (spec.type === 'checkbox') {
        selectedSpecs.value[spec.name] = []
      }
    })
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 获取推荐商品
const loadRecommendProducts = async () => {
  try {
    const res = await getRecommendProducts(route.params.id)
    recommendList.value = res.data
  } catch (error) {
    console.error('获取推荐商品失败:', error)
  }
}

// 处理规格变化
const handleSpecChange = () => {
  // 根据选择的规格更新商品信息
  // 这里需要调用后端接口获取对应规格的商品信息
  console.log('规格变化:', selectedSpecs.value)
}

// 检查规格是否可选
const isSpecAvailable = (specName, value) => {
  // 根据库存和规格组合判断是否可选
  return true
}

// 处理数量变化
const handleQuantityChange = (value) => {
  quantity.value = value
}

// 处理加入购物车
const handleAddToCart = async () => {
  if (!isAddToCartEnabled.value) {
    ElMessage.warning('请选择商品规格')
    return
  }

  try {
    await addToCart({
      productId: product.value.id,
      quantity: quantity.value,
      specifications: selectedSpecs.value
    })
    
    ElMessage.success('添加成功')
    // 更新购物车数量
    await cartStore.updateCartCount()
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 处理立即购买
const handleBuyNow = async () => {
  if (!isAddToCartEnabled.value) {
    ElMessage.warning('请选择商品规格')
    return
  }

  try {
    const res = await addToCart({
      productId: product.value.id,
      quantity: quantity.value,
      specifications: selectedSpecs.value
    })
    
    // 跳转到订单确认页
    router.push({
      path: '/order/confirm',
      query: { items: res.data.id }
    })
  } catch (error) {
    console.error('购买失败:', error)
    ElMessage.error('购买失败')
  }
}

// 处理收藏
const handleToggleFavorite = async () => {
  try {
    await toggleFavorite(product.value.id)
    isFavorite.value = !isFavorite.value
    ElMessage.success(isFavorite.value ? '收藏成功' : '取消收藏')
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理分享
const handleShare = async () => {
  try {
    const res = await shareProduct(product.value.id)
    // 调用分享接口
    await navigator.share({
      title: product.value.name,
      text: product.value.description,
      url: res.data.shareUrl
    })
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败')
  }
}

// 处理商品点击
const handleProductClick = (item) => {
  router.push(`/product/${item.id}`)
}

// 初始化
onMounted(() => {
  loadProductDetail()
  loadRecommendProducts()
})
</script>

<style lang="scss" scoped>
.product-detail-container {
  padding: 20px;
  
  .product-content {
    max-width: 1200px;
    margin: 0 auto;
    
    .product-basic {
      display: flex;
      gap: 40px;
      margin-bottom: 40px;
      
      .product-gallery {
        width: 500px;
        
        .product-image {
          width: 100%;
          height: 100%;
          border-radius: 4px;
        }
      }
      
      .product-info {
        flex: 1;
        
        .product-name {
          margin: 0 0 20px;
          font-size: 24px;
          font-weight: 500;
          color: #303133;
        }
        
        .product-price {
          margin-bottom: 20px;
          
          .current-price {
            font-size: 28px;
            font-weight: 500;
            color: #f56c6c;
          }
          
          .original-price {
            margin-left: 10px;
            font-size: 16px;
            color: #909399;
            text-decoration: line-through;
          }
        }
        
        .product-tags {
          display: flex;
          gap: 10px;
          margin-bottom: 20px;
        }
        
        .product-stock {
          margin-bottom: 20px;
          font-size: 14px;
          color: #606266;
          
          .stock-warning {
            color: #f56c6c;
          }
        }
        
        .product-specs {
          margin-bottom: 20px;
          
          .spec-item {
            display: flex;
            margin-bottom: 15px;
            
            .spec-name {
              width: 80px;
              font-size: 14px;
              color: #606266;
            }
            
            .spec-values {
              flex: 1;
              
              :deep(.el-radio),
              :deep(.el-checkbox) {
                margin-right: 20px;
                margin-bottom: 10px;
              }
            }
          }
        }
        
        .product-quantity {
          display: flex;
          align-items: center;
          margin-bottom: 30px;
          
          .quantity-label {
            width: 80px;
            font-size: 14px;
            color: #606266;
          }
        }
        
        .product-actions {
          display: flex;
          gap: 15px;
          
          .el-button {
            flex: 1;
          }
        }
      }
    }
    
    .product-detail {
      margin-bottom: 40px;
      
      .detail-content {
        padding: 20px;
        
        :deep(img) {
          max-width: 100%;
          height: auto;
        }
      }
      
      .service-content {
        padding: 20px;
        
        h3 {
          margin: 0 0 15px;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }
        
        p {
          margin: 0 0 20px;
          font-size: 14px;
          color: #606266;
          line-height: 1.6;
        }
      }
    }
    
    .recommend-products {
      h3 {
        margin: 0 0 20px;
        font-size: 18px;
        font-weight: 500;
      }
      
      .product-card {
        margin-bottom: 20px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        
        .product-image {
          width: 100%;
          height: 200px;
        }
        
        .product-info {
          padding: 10px;
          
          .product-name {
            margin: 0 0 8px;
            font-size: 14px;
            font-weight: 500;
            color: #303133;
            @include text-ellipsis;
          }
          
          .product-price {
            margin: 0;
            font-size: 16px;
            font-weight: 500;
            color: #f56c6c;
          }
        }
      }
    }
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .product-detail-container {
    .product-content {
      .product-basic {
        flex-direction: column;
        
        .product-gallery {
          width: 100%;
        }
      }
      
      .product-actions {
        flex-direction: column;
      }
    }
  }
}
</style> 